package com.huwaiwai.jvm.d20191231;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 歪大哥😁
 * @date 2019-12-31.
 */
public class ConditionTest {

    private static ReentrantLock lock = new ReentrantLock();


    public static void main(String[] args) throws InterruptedException {
        Condition c1 = lock.newCondition();
        Condition c2 = lock.newCondition();
        new Thread(() -> {
            String name = Thread.currentThread().getName();
            long startTime = System.currentTimeMillis();
            System.out.println(name + "  等待c1");
            try {
                lock.lock();
                c1.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            System.out.println(name + "  等待c1结束 被唤醒 耗时:" + (System.currentTimeMillis() - startTime));
        }).start();

        new Thread(() -> {
            String name = Thread.currentThread().getName();
            long startTime = System.currentTimeMillis();
            System.out.println(name + "  等待c1");
            try {
                lock.lock();
                c1.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            System.out.println(name + "  等待c1结束 被唤醒 耗时:" + (System.currentTimeMillis() - startTime));
        }).start();


        new Thread(() -> {
            String name = Thread.currentThread().getName();
            long startTime = System.currentTimeMillis();
            System.out.println(name + "  等待c2");
            try {
                lock.lock();
                c2.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            System.out.println(name + "  等待c2结束 被唤醒 耗时:" + (System.currentTimeMillis() - startTime));
        }).start();

        new Thread(() -> {
            String name = Thread.currentThread().getName();
            long startTime = System.currentTimeMillis();
            System.out.println(name + "  等待c2");
            try {
                lock.lock();
                c2.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            System.out.println(name + "  等待c2结束 被唤醒 耗时:" + (System.currentTimeMillis() - startTime));
        }).start();
        Thread.sleep(1000L);
        lock.lock();
        c1.signalAll();
        lock.unlock();
        Thread.sleep(1000L);
        lock.lock();
        c2.signalAll();
        lock.unlock();
        Thread.sleep(2000L);
    }
}
